package com.witframework.meta.service.impl;


import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.witframework.core.logic.BaseService;
import com.witframework.meta.MetaEntity;
import com.witframework.meta.MetaEntityField;
import com.witframework.meta.dao.MetaEntityDao;
import com.witframework.meta.dao.MetaEntityFieldDao;
import com.witframework.meta.service.MetaEntityService;

/**
* EntityMeta service implement
*/

@Service("metaEntityService")
@Transactional
public class MetaEntityServiceImpl extends BaseService implements MetaEntityService{

	MetaEntityDao<MetaEntity> dao;
	MetaEntityFieldDao<MetaEntityField> entityFieldMetaDao;
	public void remove(String... ids) {
		for(String id:ids){
			MetaEntity entity=dao.findById(id);
			List<MetaEntityField> fieldList=entity.getFields();
			for(MetaEntityField f:fieldList){
				entityFieldMetaDao.delete(f);
			}
			dao.delete(entity);
		}
	}
	public void saveOrUpdate(MetaEntity metaEntity) {
		if(!dao.isUnique(metaEntity, "className")){
			MetaEntity en=dao.getBy("className",metaEntity.getClassName());	
			dao.deleteById(metaEntity.getId());		
			entityFieldMetaDao.deleteBy("metaEntity.id",metaEntity.getId());
		}		
		dao.saveOrUpdate(metaEntity);
		List<MetaEntityField> oldFields=entityFieldMetaDao.findBy("metaEntity.id",metaEntity.getId());
		List<String> oldIds=new ArrayList<String>();
		for(MetaEntityField entityField:oldFields){
			oldIds.add(entityField.getId());
		}
		for(MetaEntityField entityField:metaEntity.getFields()){
			entityField.setMetaEntity(metaEntity);
			entityFieldMetaDao.saveOrUpdate(entityField);
			if(oldIds.contains(entityField.getId()))
				oldIds.remove(entityField.getId());
		}
		for(String id:oldIds){
			entityFieldMetaDao.deleteById(id);
		}
	}

	@Autowired
	public void setDao(MetaEntityDao<MetaEntity> dao) {
		this.dao = dao;
		super.setDao(dao);
	}
	@Autowired
	public void setEntityFieldMetaDao(MetaEntityFieldDao<MetaEntityField> entityFieldMetaDao) {
		this.entityFieldMetaDao = entityFieldMetaDao;
	}
}